import fs from "fs";
import { rollup } from "rollup";
import typescript from "@rollup/plugin-typescript";
import { terser } from "rollup-plugin-terser";
import url from "@rollup/plugin-url";
import progress from "rollup-plugin-progress";

import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";

const pkg = JSON.parse(fs.readFileSync("./package.json").toString());

const external = [
  ...Object.keys(pkg.peerDependencies || {}),
  // ...Object.keys(pkg.dependencies || {}),
  // "dayjs/plugin/isBetween",
  // "dayjs/plugin/isSameOrAfter",
  // "rc-picker/es/locale/zh_CN",
  // "rc-picker/es/generate/dayjs",
];

function build(inputOptions, outputOptions) {
  return rollup(inputOptions).then((bundle) => bundle.write(outputOptions));
}

async function buildCjs() {
  await build(
    {
      input: ["src/index.ts"],
      external,
      plugins: [
        nodeResolve(),
        commonjs(),
        progress(),
        typescript({}),
        terser(),
        url(),
      ],
    },
    {
      sourcemap: true,
      compact: true,
      format: "cjs",
      file: pkg.main,
      exports: "auto",
    }
  );
}

async function buildES() {
  await build(
    {
      input: ["src/index.ts"],
      external,
      plugins: [
        nodeResolve(),
        commonjs(),
        progress(),
        typescript({}),
        /**
         * 不能使用 terser 压缩，压缩后 *偶然* 出现在项目中报
         * function `Function statements require a function name`
         */
        // terser(),
        url(),
      ],
    },
    {
      sourcemap: true,
      compact: true,
      format: "es",
      file: pkg.module,
    }
  );
}

async function run() {
  await buildES();
  // await buildCjs();
}

run();
